package com.diaohaiwen.basic.websockt.service;

import com.diaohaiwen.basic.websockt.mapper.NoticeMapper;
import com.diaohaiwen.basic.websockt.obj.model.Notice;
import com.diaohaiwen.basic.websockt.obj.query.NoticeQuery;
import com.diaohaiwen.basic.websockt.obj.vo.NoticeVo;
import com.diaohaiwen.common.enums.NoticeEnum;
import com.diaohaiwen.common.obj.page.CurrentPageVo;
import com.diaohaiwen.framework.authority.AuthorityUtil;
import com.mybatisflex.core.constant.SqlConsts;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryOrderBy;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import static com.diaohaiwen.basic.websockt.obj.model.table.NoticeTableDef.NOTICE;

/**
 * @author 刁海文
 * @since 2023/12/9 22:23
 */
@Service
public class HistoryService {

    @Resource
    NoticeMapper noticeMapper;

    public CurrentPageVo<NoticeVo> pages(NoticeEnum noticeType, NoticeQuery query) {

        Page<Notice> paginate = noticeMapper.paginate(query.getPage().getCurrent(), query.getPage().getSize(), QueryWrapper.create()
                .where(NOTICE.NOTICE_TYPE.eq(noticeType))
                .and(wrapper -> {
                    wrapper.or(w -> {
                        w.and(NOTICE.SENDER_ID.eq(AuthorityUtil.getLoginId())).and(NOTICE.RECEIVER_ID.eq(query.getReceiverId()));
                    });
                    wrapper.or(w -> {
                        w.and(NOTICE.SENDER_ID.eq(query.getReceiverId())).and(NOTICE.RECEIVER_ID.eq(AuthorityUtil.getLoginId()));
                    });
                })
                .orderBy(new QueryOrderBy(NOTICE.CREATED_TIME, SqlConsts.DESC))
        );
        List<NoticeVo> records = paginate.getRecords().stream().map(Notice::toVO).collect(Collectors.toList());
        Collections.reverse(records);
        return CurrentPageVo.create(paginate.getTotalRow(), records);
    }
}
